﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace DIProject.Util
{
	/// <summary>
	/// Персональные настройки приложения для каждого пользователя
	/// </summary>
	public class Setting
	{
		public const string FOLDER = "DIAPTEKA";
		/// <summary>
		/// извлекаем из хранилища документ с настройками
		/// </summary>
		/// <returns></returns>
		public static XmlDocument GetSettingDocument()
		{	return XmlIniFile.Document;
		/* Ниже заремарено: чтение документа см. ApplicationContext.cs и XmlIniFile.cs метод Load() (mf 12.06.2006 18.06)
			using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForDomain())
			{
				string[] dn = isoFile.GetDirectoryNames("*");
				List<string> dirList = new List<string>(dn);
				if (!dirList.Contains(FOLDER))
				{
					isoFile.CreateDirectory(FOLDER);
				}
				string[] files = isoFile.GetFileNames(FOLDER + "/");
				if (files == null)
					return null;
				if (files.Length < 1)
					return null;
				List<string> filesG = new List<string>(files);
				if (!filesG.Contains(Environment.UserName))
					return null;
				try
				{
					string fPath = FOLDER + "/" + Environment.UserName;
					using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fPath, FileMode.Open, FileAccess.Read, isoFile))
					{
						using (StreamReader reader = new StreamReader(isoStream))
						{
							string str = reader.ReadToEnd();
							XmlDocument doc = new XmlDocument();
							doc.LoadXml(str);
							return doc;
						}
					}
				}
				catch (FileNotFoundException)// fnfe)
				{
					return null;
				}
				catch (Exception)// ee)
				{
					return null;
				}
			}
			//return null;*/
		}

		/// <summary>
		/// помещаем в хранилище документ с настройками
		/// </summary>
		public static Int32 SetSettingDocument(XmlDocument doc)
		{
		/* Ниже заремарено: запись документа см. ApplicationContext.cs и XmlIniFile.cs метод Save() (mf 12.06.2006 18.06)
			using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForDomain())
			{
				string[] files = isoFile.GetFileNames(FOLDER + "/");
				if (files == null)
					return -1;
		*/	/*	if (files.Length < 1)
					return -2;*/
		/*		List<string> filesG = new List<string>(files);
				if (filesG.Contains(Environment.UserName))
				{
					isoFile.DeleteFile(FOLDER + "/" + Environment.UserName);
				}
				try
				{
					string fPath = FOLDER + "/" + Environment.UserName;
					using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fPath, FileMode.OpenOrCreate, FileAccess.Write, isoFile))
					{
						using (StreamWriter writer = new StreamWriter(isoStream))
						{
							writer.Write(doc.OuterXml);
						}
					}
				}
				catch (Exception ee)
				{
					throw new Exception("Невозможно сохранить настройки пользователя.",ee);
				}
			}
		*/	return 0;
		}
		/// <summary>
		/// Путь к папке с накладными для поставщика
		/// </summary>
		/// <param name="seller"></param>
		/// <returns></returns>
		public static string GetWaybillsPath(string seller)
		{
			string tmpSeller = seller.Replace("\"", "'");
			XmlDocument doc = GetSettingDocument();
			if (doc == null)
				return null;
			XmlNode root = doc.DocumentElement;
			XmlNode node = root.SelectSingleNode("sellers/item[@id=\"" + tmpSeller + "\"]");
			if (node == null)
				return null;
			node = node.SelectSingleNode("waybillPath");
			if (node == null)
				return null;
			return node.InnerText;

		}
        public static Util.NkldType GetWaybillsNkldType(string seller)
        {
            string tmpSeller = seller.Replace("\"", "'");
            XmlDocument doc = GetSettingDocument();
            if (doc == null)
                return Util.NkldType.EMPTY;
            XmlNode root = doc.DocumentElement;
            XmlNode node = root.SelectSingleNode("sellers/item[@id=\"" + tmpSeller + "\"]");
            if (node == null)
                return Util.NkldType.EMPTY;
            XmlAttribute type = node.Attributes["type"];
            if (type == null)
                return NkldType.EMPTY;
            NkldType result = (NkldType)Enum.Parse(typeof(NkldType), type.Value);
            return result;
        }
		/// <summary>
		/// устанавливаем путь к папке с накладными для поставщика
		/// </summary>
		/// <param name="seller">наименование поставщика</param>
		/// <param name="sPath">путь к папке с его накладными</param>
		/// <returns></returns>
		public static bool SetWaybillsPath(string seller, string sPath,Util.NkldType nType)
		{
			string tmpSeller = seller.Replace("\"", "'");
			XmlDocument doc = GetSettingDocument();
			if (doc == null)
			{
				doc = new XmlDocument();
			}
			XmlNode tmp = GetNode("root/sellers", doc);
			XmlNode t = tmp.SelectSingleNode("item[@id=\"" + tmpSeller + "\"]");
			XmlNode waybillPath;
            if (t == null)
            {
                t = tmp.OwnerDocument.CreateElement("item");
                XmlAttribute id = tmp.OwnerDocument.CreateAttribute("id");
                id.Value = tmpSeller;
                t.Attributes.Append(id);
                XmlAttribute type = tmp.OwnerDocument.CreateAttribute("type");
                type.Value = nType.ToString();
                t.Attributes.Append(type);
                tmp.AppendChild(t);
            }
            else
            {
                XmlAttribute type = tmp.OwnerDocument.CreateAttribute("type");
                type.Value = nType.ToString();
                t.Attributes.Append(type);
                tmp.AppendChild(t);
            }
			waybillPath = t.SelectSingleNode("waybillPath");
			if (waybillPath == null)
			{
				waybillPath = t.OwnerDocument.CreateElement("waybillPath");
				t.AppendChild(waybillPath);
			}
			waybillPath.InnerText = sPath;
			SetSettingDocument(doc);
			return true;
		}
		/// <summary>
		/// получаем ноду по пути
		/// </summary>
		/// <param name="xPath">путь</param>
		/// <param name="node">нода относительно которой ищем</param>
		/// <returns></returns>
		public static XmlNode GetNode(string xPath, XmlNode node)
		{
			string[] nodes = xPath.Split(new char[] { '/' });
			if (nodes.Length < 1)
				throw new DIException("Неверный путь. Невозможно вернуть XMLNode");
			XmlNode tmp = node;
			XmlDocument doc;
			if (node is XmlDocument)
			{
				doc = node as XmlDocument;
			}
			else
			{
				doc = node.OwnerDocument;
			}
			foreach (string str in nodes)
			{
				XmlNode tmp2 = tmp.SelectSingleNode(str);
				if (tmp2 == null)
				{
					tmp2 = doc.CreateElement(str);
					tmp.AppendChild(tmp2);
				}
				tmp = tmp2;
			}
			return tmp;
		}
        public static string FirmName
        {
            get
            {
                try
                {
                    string str = System.Configuration.ConfigurationManager.AppSettings["NameAptek"];
                    if (string.IsNullOrEmpty(str))
                        return string.Empty;
                    return str;
                }
                catch (Exception ee)
                {
                    return string.Empty;
                }
            }

        }
        /// <summary>
        /// мы в оффисе или в филлиале
        /// </summary>
        public static bool IsOffice
        {
            get
            {
                try
                {
                    string str = System.Configuration.ConfigurationManager.AppSettings["IsOffice"];
                    if (string.IsNullOrEmpty(str))
                        return false;
                    if (str == "1")
                        return true;
                    return false;
                }
                catch (Exception ee)
                {
                    return false;
                }
            }
        }
        private static DataSets.Settings.FirmSettingsDataTable firmSetting = null;
       /// <summary>
       /// получаем - устанавливаем настройки
       /// </summary>
        public static XmlDocument FirmSetting
        {
            get
            {
                XmlDocument _res = null;
                if (firmSetting == null)
                {
                    DataSets.SettingsTableAdapters.FirmSettingsTableAdapter adapt = new DIProject.DataSets.SettingsTableAdapters.FirmSettingsTableAdapter();
                    firmSetting = adapt.GetData();
                }
                DataSets.Settings.FirmSettingsRow fsr = firmSetting.Rows[0] as DataSets.Settings.FirmSettingsRow;
                if (fsr.IsProfileNull())
                    return _res;
                string str = fsr.Profile;
                _res = new XmlDocument();
                _res.LoadXml(str);
                return _res;
            }
            set
            {
                firmSetting = null;
                XmlDocument _res = null;
                DataSets.SettingsTableAdapters.FirmSettingsTableAdapter adapt = new DIProject.DataSets.SettingsTableAdapters.FirmSettingsTableAdapter();
                firmSetting = adapt.GetData();                
                DataSets.Settings.FirmSettingsRow fsr = firmSetting.Rows[0] as DataSets.Settings.FirmSettingsRow;
                fsr.Profile = value.OuterXml;
                fsr.MD = DateTime.Now;
                fsr.MW = FirstForm.Login;
                adapt.Update(firmSetting);
            }
        }
        public static string GetCashPassword(Int32 deptId)
        {
            string template = @"root/departments/department[@id={0}]";
            XmlDocument doc = Setting.FirmSetting;
            if (doc == null)
                return string.Empty;
            string path = string.Format(template, deptId);
            XmlNode node = doc.SelectSingleNode(path);
            if (node == null)
                return string.Empty;
            node = node.SelectSingleNode("cashPassport");
            string res = node.InnerText;
            return res;
        }
        public static void SetCashPassword(Int32 deptId, string password)
        {
            string template = @"root/departments/department[@id={0}]";
            XmlDocument doc = Setting.FirmSetting;
            if (doc == null)
            {
                doc = CreateDoc();
            }
            XmlNode node = AddOrGetDepartment(doc, deptId);

            node.InnerText = GetHash(password);
            Setting.FirmSetting = doc;
        }
        public static XmlDocument CreateDoc()
        {
            XmlDocument res = new XmlDocument();
            XmlDeclaration decl = res.CreateXmlDeclaration("1.0", "utf-8","");
            res.AppendChild(decl);
            XmlElement root = res.CreateElement("root");
            res.AppendChild(root);
            XmlElement departments = res.CreateElement("departments");
            res.AppendChild(departments);
            return res;
        }
        public static XmlNode AddOrGetDepartment(XmlDocument doc, Int32 deptId)
        {
            string template = @"root/departments/department[@id={0}]";
            string path = string.Format(template, deptId);
            XmlNode node = doc.SelectSingleNode(path);
            if (node != null)
            {
                node=node.SelectSingleNode("cashPassport");
                return node;
            }
            node = doc.SelectSingleNode("root/departments");
            XmlElement department = doc.CreateElement("department");
            node.AppendChild(department);
            XmlAttribute atr = doc.CreateAttribute("id");
            atr.Value = deptId.ToString();
            department.Attributes.Append(atr);
            XmlElement cashPassport = doc.CreateElement("cashPassport");
            department.AppendChild(cashPassport);
            return cashPassport;
        }
        public static string GetHash(string str)
        {
            DateTime dt = DateTime.Today;
            string s = "lkjhaslkdjfhiwefhjbnclksadjflsdfcsalkdjh";
            string buf = dt.ToString("d") + s + str;
            SHA512Managed m = new SHA512Managed();
            Encoding e = Encoding.Unicode;
            byte[] b = e.GetBytes(buf);
            byte[] res = m.ComputeHash(b);
            string res1 = System.Convert.ToBase64String(res);
            return res1;
        }
	}
}
